<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>音频可视化</title>
</head>

<body>
  <h1>
    音频可视化Demo
  </h1>
  <canvas id="visualizer" width="400" height="150" style="border: solid 1px;padding: 10px;"></canvas>


  <script>
    const canvas = document.getElementById('visualizer');
    const ctx = canvas.getContext('2d');
    const stream = navigator.mediaDevices.getUserMedia({ audio: true });
    let bufferLength;
    let dataArray;

    stream.then((micStream) => {
      const audioContext = new AudioContext();
      const source = audioContext.createMediaStreamSource(micStream);
      const scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1);



      scriptProcessor.onaudioprocess = (event) => {

        const inputBuffer = event.inputBuffer;
        bufferLength = inputBuffer.getChannelData(0).length;
        dataArray = new Float32Array(bufferLength);

        for (let i = 0; i < bufferLength; i++) {
          const sample = inputBuffer.getChannelData(0)[i];
          dataArray[i] = sample;
        }

        drawWaveform();

      };

      source.connect(scriptProcessor);
      scriptProcessor.connect(audioContext.destination);
    });

    function drawWaveform() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      ctx.lineWidth = 1;
      ctx.strokeStyle = 'rgb(150, 150, 150)';
      ctx.beginPath();







      const sliceWidth = canvas.width * 1.0 / bufferLength;






      let x = 0;

      for (let i = 0; i < bufferLength; i++) {
        const v = dataArray[i] / 2;
        const y = v * canvas.height / 2;
        if (i === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
        x += sliceWidth;
      }

      ctx.stroke();
    }
  </script>
</body>

</html>